package com.bootdo.clouddo.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.clouddo.controller.QiniuImageUploader.MyRet;
import com.bootdo.clouddo.service.file.IFileService;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;
import com.qiniu.common.QiniuException;
import sun.net.www.protocol.https.HttpsURLConnectionImpl;

@RestController
@RequestMapping("/file")
public class FileController{
	
	@Autowired
	private IFileService biz;
	
	@Value("${qiniu.bucket}")
	String bucket_cn;
	
	@Value("${qiniu.domain}")
	String domain;
	
	
	@GetMapping("/getUpToken")
	public R getUpToken(){
		return R.ok().put("uptoken", biz.getUpToken(bucket_cn, 3600));
	}
	
	
	@GetMapping("/downloadFile")
	public void downloadFile(String key, HttpServletResponse response){
		try {
			response.sendRedirect(biz.getUrl(key, domain, 3600));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	@GetMapping("/deleteFile")
	public R delete(String key){
		try {
			biz.delete(key, bucket_cn);
			return R.ok();
		} catch (QiniuException e) {
			e.printStackTrace();
			return R.error(e.response.error);
		}
	}
	
	@PostMapping("/upload/{type}")
    public R upload(@PathVariable String type, @RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
		String fileName = type + "/" +new SimpleDateFormat("yyyy-MM-dd/").format(new Date())+StringUtils.getUUID()+"/"+file.getOriginalFilename().replace(" ", "");
		MyRet ret = QiniuImageUploader.newInstance().upload(file.getBytes(), fileName);
		if(ret != null) {
			return R.data(ret);
		}
		return R.error();
    }

	@RequestMapping(value = "/getJuejinImg/{y}/{m}/{d}/{id}",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getJuejinImg(@PathVariable String y, @PathVariable String m, @PathVariable String d, @PathVariable String id){
		String url = "https://user-gold-cdn.xitu.io/"+y+"/"+m+"/"+d+"/"+id;
		try {
			return image2byte(url);
		} catch (IOException e) {
			System.out.println("获取网络图片出现异常，图片路径为：" + url);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 图片转为byte数组
	 *
	 * @param path
	 * @return
	 */
	public static byte[] image2byte(String path) throws IOException {
		byte[] data = null;
		URL url = null;
		InputStream input = null;
		try{
			url = new URL(path);
			HttpsURLConnectionImpl httpUrl = (HttpsURLConnectionImpl) url.openConnection();
			httpUrl.connect();
			httpUrl.getInputStream();
			input = httpUrl.getInputStream();
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int numBytesRead = 0;
		while ((numBytesRead = input.read(buf)) != -1) {
			output.write(buf, 0, numBytesRead);
		}
		data = output.toByteArray();
		output.close();
		input.close();
		return data;
	}
}
